package com.liu.qqRobot.poke.runnable;

import cn.hutool.core.img.ImgUtil;
import com.liu.mybatisPlus.poke.entity.base.Poke;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class SavePokeImgRunnable implements Runnable {

    private final Poke poke;

    private final CountDownLatch countDownLatch;

    public SavePokeImgRunnable(Poke poke, CountDownLatch countDownLatch) {
        this.poke = poke;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        try {
            String[] split = poke.getImgUrl().split("/");
            int length = split.length;
            String imgName = split[length - 1];
            String localUrl = "src/main/resources/pokeImage/" + imgName;
            File file = new File(localUrl);
            if (!file.exists()) {
                file.mkdirs();
            }
            InputStream inputStream = new URL(poke.getImgUrl()).openConnection().getInputStream();
            BufferedImage bufferedImage = ImgUtil.read(inputStream);
            ImageIO.write(bufferedImage, "png", file);
            poke.setLocalUrl(localUrl);
        } catch (Exception e) {
            log.error("宝可梦：{}保存图片失败，失败原因：{}", poke.getName(), e.getMessage(), e);
        } finally {
            countDownLatch.countDown();
        }
    }
}
